package com.cardvalue.sys.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.cardvalue.sys.R;
import com.cardvalue.sys.activity.ConfirmListActivity;
import com.cardvalue.sys.base.BaseFragment;
import com.cardvalue.sys.cache.LocalCache;
import com.cardvalue.sys.code.CallBackCode;
import com.cardvalue.sys.entity.Apply;
import com.cardvalue.sys.entity.PostCreateAuth;
import com.cardvalue.sys.entity.VerifyImgCode;
import com.cardvalue.sys.mode.Service;
import com.cardvalue.sys.mode.UserService;
import com.cardvalue.sys.newnetwork.Config;
import com.cardvalue.sys.tool.CheckingForm;
import com.cardvalue.sys.tool.LocationUtil;
import com.cardvalue.sys.tool.MessageBox;
import com.cardvalue.sys.tool.Utiltools;

import java.util.Date;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.fraudmetrix.android.FMAgent;
import io.realm.Realm;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 对私的绑卡界面
 * Created by Administrator on 2016/6/13.
 */
public class BankCardPrivateFragment extends BaseFragment{
    @Bind(R.id.open_names) EditText   directDebitAcctName;//还款账户名
    @Bind(R.id.account_cardids) EditText   directDebitAcctId;//身份证
    @Bind(R.id.open_banks) TextView   directDebitBankName;//开户银行
    @Bind(R.id.bank_accounts) EditText   directDebitAcctNo;//银行账号
    @Bind(R.id.bank_account_numbers) EditText  directDebitAcctPhone ;//银行预留手机号
    @Bind(R.id.bank_getCodes) Button bank_getCodes;// 获取验证码按钮
    @Bind(R.id.bank_yanzheng) EditText   mobilePhoneVerifyCode;//输入验证码
    @Bind(R.id.bank_button) Button bank_button ;//绑定银行卡
    @Bind(R.id.bank_crark_tk3)  TextView bank_crark_tk3; //融资协议页面
    @Bind(R.id.bank_xieyi)  CheckBox bank_xieyi;//check 协议(是否选中)

    private String smsNumber ="";  //这是发送短信的手机号码
    private String  imageVerifyCode;//用户输入的图形验证码
    private Service.GetImgCode  VerifyImgCodeService;//获取图形验证码
    private Timer timer=new Timer(); // 控制获取验证码按钮是否显示
    public static boolean isRefrensh = true;//判断是否可以弹出dialog
    private int codeExpirDate = 0;  // 验证码有效期
    private String  verifyCode =""; // 手机验证码
    private Realm realm;
    private Retrofit retrofit;
    public static   Handler handler;
    private UserService  userService;//
    private   String directDebitBankCode;//银行卡的行号
    private   String mdirectDebitAcctName;
    private    String   mdirectDebitAcctId;
    private  String mdirectDebitBankName;
    private String   mdirectDebitAcctNo;
    private  String mdirectDebitAcctPhone;
    private  String mmobilePhoneVerifyCode;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.bank_card_base_private,container,false);
        ButterKnife.bind(this,view);
        userService=new UserService(getActivity());
        realm=Realm.getDefaultInstance();
        dialog=new ProgressDialog(getActivity(),R.style.dialog);
        retrofit = new Retrofit.Builder()
                .baseUrl(Config.getServerIp())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what==0){//图形验证码
                    getImage();
                }else if(msg.what==1){//手机验证码
                    Bundle bundle = msg.getData();
                    imageVerifyCode=bundle.get("imageVerifyCode").toString().trim();
                    getImage();
                }else if(msg.what== CallBackCode.CALLBACK_MSG_GETBANK_PRIVATE){//选择银行卡
                    Bundle bundle=msg.getData();
                    directDebitBankName.setText(bundle.get("title").toString().trim());
                    directDebitBankCode=bundle.get("id").toString().trim();
                }
            }
        };
        setData();
        return view;
    }

    @OnClick({R.id.bank_getCodes,R.id.bank_crark_tk3,R.id.open_banks,R.id.bank_button}) void click(View view){
        switch (view.getId()){
            case R.id.bank_getCodes://获取验证码
                getImage();
                break;
            case R.id.bank_crark_tk3://融资协议页面
                break;
            case R.id.open_banks://开户银行
                Intent intentBank=new Intent(getActivity(), ConfirmListActivity.class) ;
                if(directDebitBankName.getText().toString().trim().toString().equals("")){
                    intentBank.putExtra("title","");
                    intentBank.putExtra("type","3");
                    intentBank.putExtra("tagName","directDebitBankName");
                    startActivity(intentBank);
                    return;
                }else{
                    intentBank.putExtra("title",directDebitBankName.getText().toString());
                    intentBank.putExtra("type","3");
                    intentBank.putExtra("tagName","directDebitBankName");
                    startActivity(intentBank);
                }
                break;
            case R.id.bank_button://提交按钮
                mdirectDebitAcctName=directDebitAcctName.getText().toString();
                mdirectDebitAcctId=directDebitAcctId.getText().toString();
                mdirectDebitBankName=directDebitBankName.getText().toString();
                mdirectDebitAcctNo=directDebitAcctNo.getText().toString();
                mdirectDebitAcctPhone=directDebitAcctPhone.getText().toString();
                mmobilePhoneVerifyCode=mobilePhoneVerifyCode.getText().toString();

                //非空判断
                if(!CheckingForm.checkForBankPrivate(mdirectDebitAcctName,mdirectDebitAcctId,mdirectDebitBankName,
                        mdirectDebitAcctNo,mdirectDebitAcctPhone,mmobilePhoneVerifyCode)){
                    MessageBox.ToastShow(CheckingForm.LastError,getActivity());
                    return;
                }else{
                    //先授权
                    PostCreateAuth task=new PostCreateAuth();
                    String blackBox = FMAgent.onEvent();
                    Map<String, String> map= LocationUtil.getMap();
                    task.setTime(new Date().toLocaleString() );
                    task.setIpAddress("");//IP地址
                    task.setBlackBox(blackBox);
                    task.setDeviceNumber(map.get("imel")==null?"":map.get("imel").toString());
                    task.setGps(map.get("ongitude")+","+map.get("atitude"));
                    WebView webview = new WebView(getActivity());
                    webview.layout(0, 0, 0, 0);
                    WebSettings settings = webview.getSettings();
                    String ua = settings.getUserAgentString();
                    task.setAgent(ua);
                    task.setType(Integer.parseInt("6"));
                    userService.getUserCreateAuthService(task, new UserService.GetPostCreateAuthCallback() {
                        @Override
                        public void success(PostCreateAuth task) {
                            updata();
                        }

                        @Override
                        public void fail(PostCreateAuth task) {

                        }

                        @Override
                        public void cancelDialog() {

                        }
                    });

                }

                break;
        }

    }


    // 更新申请
    public void updata(){
        Apply apply=new Apply();
        apply.setDirectDebitBankCode(directDebitBankCode.trim());
        apply.setDirectDebitAcctName(mdirectDebitAcctName);
        apply.setDirectDebitAcctId(mdirectDebitAcctId);
        apply.setDirectDebitBankName(mdirectDebitBankName);
        apply.setDirectDebitAcctNo(mdirectDebitAcctNo);
        apply.setDirectDebitAcctPhone(mdirectDebitAcctPhone);
        apply.setMobilePhoneVerifyCode(mmobilePhoneVerifyCode);
        userService.GetUpdateApplication(apply, new UserService.GetApplyCallback() {
            @Override
            public void success(Apply apply) {

            }

            @Override
            public void fail(String msg) {

            }

            @Override
            public void cancelDialog() {

            }
        });
    }


    //设置
    public void setData() {
        //  验卡信息是否可编辑 isBankInfoEditable 0：不可编辑 1：可编辑  最新申请的数据
        Apply results1 = realm.where(Apply.class).equalTo("creditId", LocalCache.getStringLocalData(getActivity(), "creditId")).findFirst();
        Utiltools.printE("对私的银行卡", "===" + JSON.toJSONString(results1));

      /*  if (results1 != null) {
            if(results1.getIsBankInfoEditable().equals("0")){//不可编辑
                directDebitBankName.setEnabled(false);
                directDebitAcctNo.setEnabled(false);
            }else if(results1.getIsBankInfoEditable().equals("1")){
                directDebitBankName.setEnabled(true);
                directDebitAcctNo.setEnabled(true);
            }
        }*/

        directDebitAcctName.setText(results1.getDirectDebitAcctName()==null?"":results1.getDirectDebitAcctName().toString());
        directDebitBankName.setText(results1.getDirectDebitBankName()==null?"":results1.getDirectDebitBankName().toString());
        directDebitAcctId.setText(results1.getDirectDebitAcctId()==null?"":results1.getDirectDebitAcctId().toString());
        directDebitAcctPhone.setText(results1.getDirectDebitAcctPhone()==null?"":results1.getDirectDebitAcctPhone().toString());
        directDebitAcctNo.setText(results1.getDirectDebitAcctNo()==null?"":results1.getDirectDebitAcctNo().toString());
    }




    /**
     * 获取图形验证码
     */
    public void getImage(){
        if(TextUtils.isEmpty(bank_getCodes.getText().toString().trim())){
            MessageBox.ToastShow("请输入手机号", getActivity());
            return;
        }
        //发送获取验证码的请求
        VerifyImgCodeService=retrofit.create(Service.GetImgCode.class);
        VerifyImgCode verifyImgCode=new VerifyImgCode();
        smsNumber=bank_getCodes.getText().toString();
        verifyImgCode.setMobilePhone(smsNumber);
        Utiltools.printE("第二次的时候是否有值：",imageVerifyCode+"hah");
        if(!TextUtils.isEmpty(imageVerifyCode)){
            verifyImgCode.setImageVerifyCode(imageVerifyCode);
        }
        Call<VerifyImgCode> repos = VerifyImgCodeService.attemptVerifyImgCode(verifyImgCode);
        repos.enqueue(new Callback<VerifyImgCode>() {
            @Override
            public void onResponse(Call<VerifyImgCode> call, Response<VerifyImgCode> response) {
                VerifyImgCode verifyImgCode=response.body();
                String error=verifyImgCode.getError()+"";
                Utiltools.printE("验证码失败后的==11=",verifyImgCode.getImgUrl()+"===url==");
                Utiltools.printE("验证码失败后的==11=",verifyImgCode.getError()+""+"===url==");
                if(!error.equals("null")){
                    MessageBox.ToastShow(verifyImgCode.getError()+"",getActivity());
                    isRefrensh=true;
                    imageVerifyCode="";
                    return;
                }
                /**
                 * 先判断url有没有值,如果url没有值，那就说明是第二次调用，是手机验证码
                 */
                if(verifyImgCode.getImgUrl()==null){
                    MessageBox.ToastShow("验证码已发送，请注意查收",getActivity());
                    codeExpirDate = 60; // 验证码的有效时间
                    verifyCode = "code"; // 标记已发验证码
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            updateVerifyCode();
                        }
                    },0,1000);
                }else{
                    /**
                     * 这里面又要判断dialog，是不是已经弹出来，
                     * 如果已经弹出来的话，就只要更新url中的图片
                     */
                    Utiltools.printE("验证码失败后的===",verifyImgCode.getImgUrl()+"===url==");
                    if(isRefrensh){
                        MessageBox.EditAlertReg(getActivity(),verifyImgCode.getImgUrl(),dialog,bank_getCodes.getText().toString().trim(),handler);
                    }else{
                        MessageBox.setVerifyCode(getActivity(),verifyImgCode.getImgUrl());
                    }
                }
            }

            @Override
            public void onFailure(Call<VerifyImgCode> call, Throwable t) {

            }
        });
    }



    /**
     * 获取验证码倒计时
     */
    public void updateVerifyCode(){
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (codeExpirDate==0){
                    bank_getCodes.setText("获取验证码");
                    bank_getCodes.setEnabled(true);            //	设置按钮恢复
                    timer.cancel();                      //	取消定时器
                    timer = new Timer();
                }else{
                    if (bank_getCodes.isEnabled())
                        bank_getCodes.setEnabled(false);
                    bank_getCodes.setText("验证码("+codeExpirDate+"秒)");
                    codeExpirDate--;
                }
            }
        });
    }

}
